package cn.xuqiudong.attachment.controller;

import cn.xuqiudong.attachment.model.Attachment;
import cn.xuqiudong.attachment.model.EditormdResponse;
import cn.xuqiudong.attachment.service.AttachmentService;
import cn.xuqiudong.common.base.model.BaseResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明 :  附件处理控制类 ：为前端提供接口
 * <p>
 *    前端的附件应该直接上传的附件服务端， 不要通过附件客户端中转一次(中转一次效率太低)。<br/>
 *    所以要求： 1. 前端要配置文件上传地址， 2. 服务端允许跨域
 *
 * </p>
 * @author  Vic.xu
 * @since  2019年12月11日 下午3:41:45
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController {

    @Resource
    private AttachmentService attachmentService;

    /**
     * 异步文件上传
     * @param file 文件
     * @param module 所属模块
     * @return BaseResponse<Attachment>
     */
    @PostMapping(value = "/upfile")
    @ResponseBody
    @CrossOrigin
    public BaseResponse<Attachment> upfile(@RequestParam("upfile") MultipartFile file,
                                           @RequestParam(required = false, defaultValue = "none") String module) {
        BaseResponse<Attachment> response = BaseResponse.success();
        if (file.isEmpty()) {
            // 204
            response.setCode(HttpStatus.NO_CONTENT.value());
            response.setMsg("没有上传任何文件");
            return response;
        }
        try {
            Attachment attachment = attachmentService.upfile(file, module);
            response.setData(attachment);
        } catch (IOException e) {
            e.printStackTrace();
            response.setCode(500);
            response.setMsg(e.getMessage());
        }
        return response;
    }

    /**
     * 批量异步文件上传
     * @param files 文件
     * @param module 所属模块
     * @return BaseResponse<List < Attachment>>
     */
    @PostMapping(value = "/upfiles")
    @ResponseBody
    @CrossOrigin
    public BaseResponse<List<Attachment>> upfiles(@RequestParam("upfiles") MultipartFile[] files,
                                                  @RequestParam(required = false, defaultValue = "none") String module) {
        BaseResponse<List<Attachment>> response = BaseResponse.success();
        if (files.length == 0) {
            // 204
            response.setCode(HttpStatus.NO_CONTENT.value());
            response.setMsg("没有上传任何文件");
            return response;
        }
        try {
            List<Attachment> result = new ArrayList<Attachment>();
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
                Attachment attachment = attachmentService.upfile(file, module);
                result.add(attachment);
            }
            response.setData(result);
        } catch (IOException e) {
            e.printStackTrace();
            response.setCode(500);
            response.setMsg(e.getMessage());
        }
        return response;
    }

    /**
     * 访问一个附件
     * @return url
     */
    @RequestMapping(value = "/visit/{id}", method = RequestMethod.GET)
    public String visit(@PathVariable int id) {
        return "redirect:" + attachmentService.getVisitUrl(id);
    }

    /**
     * 附件详情
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public BaseResponse detail(@PathVariable int id) {
        Attachment attachment = attachmentService.selectAttachmentById(id);
        return BaseResponse.success(attachment);
    }

    /**
     * 访问一个空附件
     * @return
     */
    @RequestMapping(value = "/visit/null", method = RequestMethod.GET)
    public String visit() {
        return "redirect:" + attachmentService.getBrokenAttachment();

    }

    /**
     * 流下载文件
     */
    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    @CrossOrigin
    public void get(HttpServletResponse response, @PathVariable int id) throws IOException {
        String aliUrl = attachmentService.getAliUrl(id);
        if (aliUrl != null) {
            response.sendRedirect(aliUrl);
            return;
        }
        Attachment attachment = attachmentService.selectAttachmentById(id);
        try {
            File file = attachment.getRealFile();
            if (file == null) {
                throw new IOException();
            }
            response.setContentType(attachment.getContentType());
            response.setHeader("Content-disposition", "attachment; filename=\"" + file.getName() + "\"");
            FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Editor.md 编辑器图片上传
     * @return
     */
    @PostMapping(value = "/mdload")
    @ResponseBody
    @CrossOrigin
    public EditormdResponse mdload(@RequestParam("editormd-image-file") MultipartFile file) {
        if (file.isEmpty()) {
            return EditormdResponse.error("没有上传任何文件");
        }
        try {
            String module = "Editor-md";
            Attachment attachment = attachmentService.upfile(file, module);
            return EditormdResponse.success(attachment.getUrl());
        } catch (IOException e) {
            e.printStackTrace();
            return EditormdResponse.error(e.getMessage());
        }
    }


}
